import pandas as pd


class Singleton(type):
    def __init__(self, *args, **kwargs):
        print("__init__")
        self.__instance = None
        super(Singleton, self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        if self.__instance is None:
            self.__instance = super(Singleton, self).__call__(*args, **kwargs)
        return self.__instance


class WordGroup(metaclass=Singleton):
    def __init__(self):
        self.filepath_sheet = "./resource/word.xlsx"
        self.df: pd.DataFrame = pd.read_excel(self.filepath_sheet)

        self.filepath_group_register = "./resource/group_register.txt"
        with open(self.filepath_group_register, 'r', encoding='utf-8') as f:
            self.group_register = f.read()
            self.group_register = self.group_register.split("\n")

    def get_group_with_chinese(self, group=None):
        """
        加载 group
        :param group: 单词组名称 不填写group得时候就是全部
        :return: 单纯的列表格式
        """
        dat = self.load_group_dataframe(group)
        return list(zip(dat['单词'].tolist(), dat['释义'].tolist()))

    def remove_group(self, groupname):
        """
        删除 词组
        :param groupname:
        :return:
        """
        index = self.df[self.df['词组'] == groupname].index
        self.df.drop(index, inplace=True)
        self.del_group(groupname)

    def load_group(self, groupname, load_history=False):
        """
        加载 某个单词组的所有单词 (只有单词没有翻译)
        :param groupname: 单词组名称
        :param load_history: 是否加载当前单词组创建之前的全部单词组数据
        :return: 单纯的列表格式
        """
        if load_history:
            index = 0
            assert groupname in self.group_register, "错误"
            for i, v in enumerate(self.group_register):
                if v == groupname:
                    index = i
                    break
            cut_list = self.group_register[0:index]
            ret = self.load_group(groupname)
            for i in cut_list:
                ret += self.load_group(i, False)
            return ret

        else:
            return self.df[self.df['词组'] == groupname]['单词'].tolist()

    def load_group_dataframe(self, group=None):
        """
        加载 某个单词组的数据
        :param group: 单词组名称 不填写的时候就是全部
        :param load_history: 是否加载当前单词组创建之前的全部单词组数据
        :return: DataFrame格式
        """
        if group:
            ret = self.df[self.df['词组'] == group]
        else:
            ret = self.df
        ret = ret[['单词', '释义']]
        return ret

    def get_all_word(self):
        """
        获取所有的单词
        :return:
        """
        return self.df['单词'].tolist()

    def get_all_group(self):
        """
        获取所有的单词组
        :return:
        """
        return self.group_register

    def del_group(self, groupname):
        """
        删除单词组
        :param groupname:
        :return:
        """
        self.group_register.remove(groupname)
        with open(self.filepath_group_register, 'w', encoding='utf-8') as f:
            f.write("\n".join(self.group_register))

    def new_group(self, groupname):
        """
        新增空的单词组
        :return:
        """
        if groupname in self.group_register:
            return "重名"
        with open(self.filepath_group_register, 'w', encoding='utf-8') as f:
            f.write("\n".join(self.group_register) + f"\n{groupname}")
        self.group_register.append(groupname)

    def append_word(self, df, group):
        df['词组'] = group
        # TODO 未开启的功能
        # df['错误次数'] = 0
        # df['是否重点标记'] = 0

        self.df = self.df.merge(df, how='outer')

    def rename_group(self, old_name, new_name):
        index: int = -1
        for _index, value in enumerate(self.group_register):
            if value == old_name:
                index = _index
                break
        if index >= 0:
            self.group_register[index] = new_name
            with open(self.filepath_group_register, 'w', encoding='utf-8') as f:
                f.write("\n".join(self.group_register))
                print("重写")
            self.df['词组'][self.df['词组'].eq(old_name)] = new_name
            print(self.df)
